import { NextResponse, NextRequest } from 'next/server';
import { prisma } from '@/lib/db';
import { auth } from '@/auth';

// 检查用户是否有权限访问项目
async function checkProjectAccess(userId: string, projectId: string) {
  const projectUser = await prisma.projectUser.findUnique({
    where: {
      userId_projectId: {
        userId,
        projectId,
      },
    },
  });
  
  return !!projectUser;
}

// 检查用户是否可以编辑任务（项目成员或任务的负责人）
async function canEditTask(userId: string, taskId: string) {
  const task = await prisma.task.findUnique({
    where: { id: taskId },
    include: {
      project: {
        include: {
          users: {
            where: { userId },
          },
        },
      },
    },
  });

  if (!task) return false;
  
  // 用户是任务的负责人
  if (task.assigneeId === userId) return true;
  
  // 用户是项目成员
  return task.project.users.length > 0;
}

// 修改 GET 方法，在返回任务数据前转换状态格式
export async function GET(request: NextRequest, context: { params: { id: string } }) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const userId = session.user.id;
    const params = await context.params;
    const taskId = params.id;

    // 获取任务
    const task = await prisma.task.findUnique({
      where: { id: taskId },
      include: {
        project: true,
        assignee: {
          select: {
            id: true,
            name: true,
            email: true,
            image: true,
          },
        },
      },
    });

    if (!task) {
      return NextResponse.json({ error: '找不到任务' }, { status: 404 });
    }

    // 验证用户是否有权限访问该任务所属的项目
    const hasAccess = await checkProjectAccess(userId, task.projectId);
    if (!hasAccess) {
      return NextResponse.json({ error: '没有权限访问此任务' }, { status: 403 });
    }

    // 导入任务状态转换函数
    const { taskStatusFromApiFormat } = await import('@/lib/utils');
    
    // 转换任务状态为前端格式
    const formattedTask = {
      ...task,
      status: taskStatusFromApiFormat(task.status)
    };

    return NextResponse.json(formattedTask);
  } catch (error) {
    console.error('获取任务详情失败:', error);
    return NextResponse.json(
      { error: '获取任务详情时出错' },
      { status: 500 }
    );
  }
}

// PATCH /api/tasks/[id] - 更新任务
export async function PATCH(request: NextRequest, context: { params: { id: string } }) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const userId = session.user.id;
    const params = await context.params;
    const taskId = params.id;

    // 验证用户是否可以编辑该任务
    const canEdit = await canEditTask(userId, taskId);
    if (!canEdit) {
      return NextResponse.json({ error: '没有权限编辑此任务' }, { status: 403 });
    }

    // 获取现有任务
    const existingTask = await prisma.task.findUnique({
      where: { id: taskId },
    });

    if (!existingTask) {
      return NextResponse.json({ error: '找不到任务' }, { status: 404 });
    }

    const body = await request.json();
    const { title, description, status, priority, assigneeId, dueDate } = body;

    // 如果提供了assigneeId，验证该用户是否为项目成员
    if (assigneeId && assigneeId !== existingTask.assigneeId) {
      const isMember = await prisma.projectUser.findUnique({
        where: {
          userId_projectId: {
            userId: assigneeId,
            projectId: existingTask.projectId,
          },
        },
      });

      if (!isMember) {
        return NextResponse.json({ error: '分配的用户不是项目成员' }, { status: 400 });
      }
    }

    // 更新任务
    const updatedTask = await prisma.$transaction(async (tx) => {
      // 更新任务数据
      const task = await tx.task.update({
        where: { id: taskId },
        data: {
          title: title || existingTask.title,
          description: description !== undefined ? description : existingTask.description,
          status: status || existingTask.status,
          priority: priority || existingTask.priority,
          assigneeId: assigneeId !== undefined ? assigneeId : existingTask.assigneeId,
          dueDate: dueDate ? new Date(dueDate) : existingTask.dueDate,
        },
        include: {
          assignee: {
            select: {
              id: true,
              name: true,
              email: true,
              image: true,
            },
          },
        },
      });

      // 创建活动记录
      await tx.activity.create({
        data: {
          userId,
          type: 'task_updated',
          entityId: taskId,
          data: { 
            taskTitle: task.title,
            projectId: task.projectId
          }
        }
      });

      // 如果状态变更为完成，创建额外的活动记录
      if (existingTask.status !== 'DONE' && task.status === 'DONE') {
        await tx.activity.create({
          data: {
            userId,
            type: 'task_completed',
            entityId: taskId,
            data: { 
              taskTitle: task.title,
              projectId: task.projectId
            }
          }
        });
      }

      // 如果分配了新的负责人，创建通知
      if (assigneeId && assigneeId !== existingTask.assigneeId && assigneeId !== userId) {
        // 创建通知
        const notification = await tx.notification.create({
          data: {
            type: 'TASK_ASSIGNED',
            title: '任务分配',
            content: `你被分配了一个新任务: ${task.title}`,
            recipients: {
              create: {
                userId: assigneeId
              }
            }
          }
        });
      }

      return task;
    });

    return NextResponse.json(updatedTask);
  } catch (error) {
    console.error('更新任务失败:', error);
    return NextResponse.json(
      { error: '更新任务时出错' },
      { status: 500 }
    );
  }
}

// PUT /api/tasks/[id] - 完全替换任务
export async function PUT(request: NextRequest, context: { params: { id: string } }) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const userId = session.user.id;
    const params = await context.params;
    const taskId = params.id;

    // 验证用户是否可以编辑该任务
    const canEdit = await canEditTask(userId, taskId);
    if (!canEdit) {
      return NextResponse.json({ error: '没有权限编辑此任务' }, { status: 403 });
    }

    // 获取现有任务以确认它存在
    const existingTask = await prisma.task.findUnique({
      where: { id: taskId },
    });

    if (!existingTask) {
      return NextResponse.json({ error: '找不到任务' }, { status: 404 });
    }

    const body = await request.json();
    const { title, description, status, priority, assigneeId, dueDate } = body;

    // 验证必要字段
    if (!title) {
      return NextResponse.json({ error: '标题是必填字段' }, { status: 400 });
    }

    // 如果提供了assigneeId，验证该用户是否为项目成员
    if (assigneeId) {
      const isMember = await prisma.projectUser.findUnique({
        where: {
          userId_projectId: {
            userId: assigneeId,
            projectId: existingTask.projectId,
          },
        },
      });

      if (!isMember) {
        return NextResponse.json({ error: '分配的用户不是项目成员' }, { status: 400 });
      }
    }

    // 更新任务
    const updatedTask = await prisma.task.update({
      where: { id: taskId },
      data: {
        title,
        description,
        status: status || 'TODO',
        priority: priority || 'MEDIUM',
        assigneeId,
        dueDate: dueDate ? new Date(dueDate) : null,
      },
      include: {
        assignee: {
          select: {
            id: true,
            name: true,
            email: true,
            image: true,
          },
        },
      },
    });

    return NextResponse.json(updatedTask);
  } catch (error) {
    console.error('替换任务失败:', error);
    return NextResponse.json(
      { error: '替换任务时出错' },
      { status: 500 }
    );
  }
}

// DELETE /api/tasks/[id] - 删除任务
export async function DELETE(request: NextRequest, context: { params: { id: string } }) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const userId = session.user.id;
    const params = await context.params;
    const taskId = params.id;

    // 验证用户是否可以编辑该任务
    const canEdit = await canEditTask(userId, taskId);
    if (!canEdit) {
      return NextResponse.json({ error: '没有权限删除此任务' }, { status: 403 });
    }

    // 获取任务信息用于记录
    const task = await prisma.task.findUnique({
      where: { id: taskId },
      select: {
        title: true,
        projectId: true
      }
    });

    if (!task) {
      return NextResponse.json({ error: '找不到任务' }, { status: 404 });
    }

    // 删除任务并记录活动
    await prisma.$transaction([
      prisma.task.delete({
        where: { id: taskId },
      }),
      prisma.activity.create({
        data: {
          userId,
          type: 'task_deleted',
          entityId: taskId,
          data: { 
            taskTitle: task.title,
            projectId: task.projectId
          }
        }
      })
    ]);

    return NextResponse.json({ message: '任务已删除' });
  } catch (error) {
    console.error('删除任务失败:', error);
    return NextResponse.json(
      { error: '删除任务时出错' },
      { status: 500 }
    );
  }
} 